<?php

namespace App\Http\Controllers\Api;

use App\Models\Renting;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

// 引入请求的http类
use GuzzleHttp\Client;

class LoginController extends Controller {
    private $gender=['未知','男','女'];
    // 业务控制器
    // 小程序登录  得到 openid
    public function login(Request $request) {
        // 小程序传入过来的code值
        $code = $request->get('code');

        // 请求小程序接口地址，得到openid
        $url = sprintf(config('wx.wxlogin'), $code);
        // 发起get请求
        $client = new Client(['timeout' => 5, 'verify' => false]);
        // 进行get请求
        $res = $client->get($url);
        $body = (string)$res->getBody();
        $arr = json_decode($body, true);
        //得到小程序登录的唯一凭证 openid
        $openid=$arr['openid'];
        //在租客表中查询此openid是否存在，存在不进行任何操作，不存在则添加
        $ret=Renting::where('openid',$openid)->first();
        if(!$ret){
            $data['openid']=$openid;
            $ret=Renting::create($data);
        }
        // 响应给小程序的数据源
        return [
            'status' => 0,
            'data' => ['openid'=>$ret->openid,'id'=>$ret->id],
            'msg'=>'小程序登录成功'
        ];
    }
    //小程序用户授权
    public function auth(Request $request){
        //当前用户id
        $id=$request->get('id');
        $data=[
            'nickname'=>$request->get('nickname'),
            'sex'=>$this->gender[$request->get('sex')],
            'avatar'=>$request->get('avatar')
        ];
        //更新数据到数据表
        Renting::where('id',$id)->update($data);
        //返回的数据
        return ['status'=>0,'msg'=>'授权成功','data'=>[]];
    }
}
